﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using UlsLogViewer.Entities;
using UlsLogViewer.Helpers;

namespace UlsLogViewer.HandlerCode
{
    public class RefreshUlsHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var latestLogTimeFromRequest = context.Request.Form["LatestLogTime"];
            var latestLogTime = DateTime.MinValue;
            if (!string.IsNullOrEmpty(latestLogTimeFromRequest))
            {
                latestLogTime = DateTime.Parse(latestLogTimeFromRequest);
            }

            //Get the location of other log files and collect all logs
            var logFiles = UlsLogCollector.GetUlsLogFiles();

            //In this date range take the first 2 most recent log files
            var allLogEntriesCombined = new List<LogEntry>();
            foreach (var filteredlogFile in logFiles.OrderByDescending(x => x.CreationTime).Take(2))
            {
                if (filteredlogFile.LogEntries != null)
                {
                    allLogEntriesCombined.AddRange(filteredlogFile.LogEntries);
                }
            }

            //Filter
            var logEntries = allLogEntriesCombined.OrderByDescending(x => x.Time).ToList();
            logEntries = logEntries.Where(x => !x.Message.Contains("RefreshUlsHandler.ashx") 
                && latestLogTime < x.Time).ToList();
            var logEntryCollection = new LogEntryCollection{LogEntries = new List<LogEntry>()};
            if (latestLogTime != DateTime.MinValue && logEntries.Any())
            {
                logEntryCollection.LogEntries = logEntries;
            }

            logEntryCollection.LatestLogTimeAsString = DateTime.Now.ToString();
            var json = SerializationHelper.Serialize<LogEntryCollection>(logEntryCollection);
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}
